package com.eascs.workflow.email.service.impl;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.app.runtime.RuntimeSetting;
import com.eascs.common.util.UuidUtil;
import com.eascs.notify.constant.ModelResult;
import com.eascs.notify.wechat.WechatMsgType;
import com.eascs.notify.wechat.WechatNotifyRequest;
import com.eascs.notify.wechat.WechatNotifyResponse;
import com.eascs.web.sso.User;
import com.eascs.workflow.common.entity.wf.ProcessTaskMain;
import com.eascs.workflow.common.entity.wf.ProcessTaskNode;
import com.eascs.workflow.common.entity.wf.TaskNodeAuditor;
import com.eascs.workflow.email.service.WechatNotifierService;
import com.eascs.workflow.email.service.WechatService;
import com.eascs.workflow.email.vo.WechatContentVo;
import com.eascs.workflow.sys.dao.SysUserDao;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

@Service
public class WechatServiceImpl implements WechatService {
	private static Logger log = LoggerFactory.getLogger(WechatServiceImpl.class);
	@Autowired
	private WechatNotifierService wechatNotifierService;
	@Autowired
	private SysUserDao sysUserDao;

	private synchronized String convertWechatContent(WechatContentVo vo) {
		// 通过指定模板名获取FreeMarker模板实例
		try {
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_24);
			configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/email/"));
			Template template = configuration.getTemplate("wechatTemplate.ftl", "UTF-8");
			StringWriter stringWriter = new StringWriter();
			// FreeMarker通过Map传递动态数据
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("wc", vo);
			template.process(map, stringWriter);
			String htmlText = stringWriter.toString();
			return htmlText;
		} catch (Exception e) {
			log.error("生成Wechat模板失败", e);
		}
		return null;
	}

	@Override
	public void notifyWechatToDo(ProcessTaskMain taskMain, List<TaskNodeAuditor> toDoList, ProcessTaskNode taskNode) {
		// 获取部署环境
		RuntimeSetting runtimeSetting = RuntimeSetting.get();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					log.info("referCode:[{}],taskCode:[{}],开始Wechat通知", taskMain.getReferCode(), taskMain.getTaskCode());
					if (runtimeSetting.getEnv().equals("prod")) {
						for (TaskNodeAuditor entry : toDoList) {
							User user = sysUserDao.getSysUserById(entry.getAuditorNo());
							String userCode = user.getCode();
							WechatNotifyRequest request = buildWechatRequest(taskMain, taskNode.getNodeName(), userCode);
							ModelResult<WechatNotifyResponse> result = wechatNotifierService.notify(request);
							if (result.isSuccess()) {
								log.info("referCode:[{}],userCode:[{}],webchat通知成功", taskMain.getReferCode(), userCode);
							} else {
								log.info("referCode:[{}],userCode:[{}],webchat通知失败,errMsg:[{}]", taskMain.getReferCode(), userCode, result.getErrMsg());
							}
						}
					}

					// 线上环境,单独给鲁胖子发一份
					//WechatNotifyRequest request = buildWechatRequest(taskMain, taskNode.getNodeName(), "SZ8164");
					//ModelResult<WechatNotifyResponse> result = wechatNotifierService.notify(request);
					//if (result.isSuccess()) {
					//	log.info("referCode:[{}],userCode:[{}],webchat通知成功", taskMain.getReferCode(), "SZ8164");
					//} else {
					//	log.info("referCode:[{}],userCode:[{}],webchat通知失败,errMsg:[{}]", taskMain.getReferCode(), "SZ8164", result.getErrMsg());
					//}
				} catch (Exception e) {
					log.error("referCode:[" + taskMain.getReferCode() + "],webchat通知失败,errorMsg:", e);
				}
			}

			/**
			 * @param taskMain
			 * @param taskNodeName
			 * @return
			 */
			private WechatNotifyRequest buildWechatRequest(ProcessTaskMain taskMain, String taskNodeName, String userCode) {
				WechatNotifyRequest request = new WechatNotifyRequest();
				String corpId = "wx12891e910218beed";
				String secret = "cBX8fe2tifObwDA3OOp8cm5pcHqsdWZOKYNkDd-uCPk2gMAyiZB-FFaGkmh1ma_a";
				request.setRequestId(UuidUtil.generateShortUuid());
				request.setCorpId(corpId);
				request.setSecret(secret);
				request.setTouser(userCode);
				request.setAgentid(0);
				request.setMsgType(WechatMsgType.REQ_MESSAGE_TYPE_TEXT);

				WechatContentVo wechatContentVo = new WechatContentVo();
				wechatContentVo.setWfType(taskMain.getProcessName());
				wechatContentVo.setLoanNo(taskMain.getReferCode());
				wechatContentVo.setProposer(taskMain.getAppliedbyName());
				wechatContentVo.setLoanDes(taskMain.getRemark());
				wechatContentVo.setTaskNodeName(taskNodeName);
				String content = convertWechatContent(wechatContentVo);
				request.setContent(content);
				return request;
			}

		}).start();
	}
}